#!/usr/bin/env bash

#get this script real directory
SOURCE="$0"
while [ -h "$SOURCE"  ]; do # resolve $SOURCE until the file is no longer a symlink
    this_script_dir="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"
    SOURCE="$(readlink "$SOURCE")"
    # if $SOURCE was a relative symlink, 
    #we need to resolve it relative to the path 
    #where the symlink file was located
    [[ $SOURCE != /*  ]] && SOURCE="$this_script_dir/$SOURCE"
done
this_script_dir="$( cd -P "$( dirname "$SOURCE"  )" && pwd  )"

log_level=${log_level:=info}
assist_dir=${assist_dir:=$this_script_dir/assist}
source $assist_dir/global.sh

################################################################################
#                                                                          80col
print_help()
{
    cat <<EOF
    useage:
        show all tool's list: $0 --list
        get the tools:        $0 --get=gcc,python

    --list              - show all tools, you can get to install
    --list_detail       - show all tools detail, you can get to install
    --get=gcc,python    - get the tool from remote

    --log_level=<debug> - control pint log on streen,trace|debug|info|warn|error|critical

    --help  - prints help screen, script will exit after printing

EOF
}

#param:$1:tool's name
get_env()
{
    if [ ! -d $env_local_dir ] ; then
        mkdir -p $env_local_dir
    fi
    local name=$1 
    local src=$host:$env_remote_path/$name/
    if [ -z "$name" ] || [ "$name" == "get" ]; then 
        vlogw "get_env param 1 is null. please set one tool's name"
        print_help;
        return 1;
    fi

    local dst=$env_local_dir/$name

    [ ! -d "$dst" ] && mkdir -p "$dst"
    cd $env_local_dir
    vlogi "$src  ->  $dst"
    local cmd_str=`cat <<EOF
    rsync -acP --delete -e 'ssh -p $port' '$src' '$dst'
EOF
`
    cmd_str=$(echo ${cmd_str})
    vlogd "execute cmd: $cmd_str"
    eval "${cmd_str}"
}

list_all()
{
   ssh -p $port "$host" "ls $env_remote_path"
}

list_all_detail()
{
   ssh -p $port "$host" "tree -L 2 $env_remote_path"
}


host=dos@s1.dos.com
port=9922
#env_remote_path=\$HOME/book/mac/git/env_config
#env_remote_path=\$HOME/git/env_config
env_remote_path=\~/git/env_config

env_local_dir=~/git/env_config
main()
{
    if [ $_arg_num_ -eq 0 ] || [ -n "$help" ] ; then
        print_help
        return 0;
    fi

    if [ -n "$list" ] ; then
        list_all
    elif [ -n "$list_detail" ] ; then
        list_all_detail
    elif [ -n "$get" ] ; then
        [ ! -d "$env_local_dir/shell" ] && get_env shell
        [ ! -d "$env_local_dir/assist" ] && get_env assist


        local tools=($(echo "${get//,/ }"))
        #echo ${tools[*]}
        for tool in ${tools[@]}
        do
            get_env $tool
        done

    fi

    return 0
}

main || exit 1 && exit 0;



